/*
 * @Author: AI Assistant
 * @Date: 2024-12-19
 * @Description: 模型、模块、模板的管理
 */
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  HttpException,
  HttpStatus,
  Query,
  Put,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { WebbaseService } from './webbase.service';
import { Module as ModuleModel } from '@libs/db/models/module.model';
import { Cube } from '@libs/db/models/cube.model';
import { Templates } from '@libs/db/models/templates.model';
import { Public } from 'src/decorations/public.decorator';
import { updateWebPage } from '../../utils/index';

@ApiTags('模型管理')
@Controller('webbase')
export class WebbaseController {
  constructor(private readonly webbaseService: WebbaseService) { }

  /**
   * 创建模型
   * @param createModuleDto 创建模型的数据
   * @returns 创建的模型数据
   */
  @Post()
  @ApiOperation({ summary: '创建模型' })
  @ApiResponse({ status: 201, description: '创建成功' })
  async create(@Body() createModuleDto: ModuleModel) {
    try {
      return await this.webbaseService.create(createModuleDto);
    } catch (error) {
      throw new HttpException(
        error.message || '创建模型失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 分页查询模型列表
   * @param query 查询参数
   * @returns 分页数据
   */
  @Post('/findAll')
  @ApiOperation({ summary: '分页查询模型列表' })
  @ApiResponse({ status: 200, description: '查询成功' })
  async findAll(@Body() query: any) {
    try {
      return await this.webbaseService.findAll(query);
    } catch (error) {
      throw new HttpException(
        error.message || '查询模型列表失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 获取全部模型列表（不带分页）
   * @returns 全部模型列表
   */
  @Get('/all')
  @ApiOperation({ summary: '获取全部模型列表' })
  @ApiResponse({ status: 200, description: '查询成功' })
  async findAllWithoutPagination() {
    try {
      return await this.webbaseService.findAllWithoutPagination();
    } catch (error) {
      throw new HttpException(
        error.message || '查询全部模型列表失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 批量删除模型
   * @param body 包含ID数组的请求体
   * @returns 删除结果
   */
  @Post('/batchDelete')
  @ApiOperation({ summary: '批量删除模型' })
  @ApiResponse({ status: 200, description: '批量删除成功' })
  async removeMany(@Body() body: { ids: string[] }) {
    try {
      const { ids } = body;
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        throw new HttpException('请提供有效的ID数组', HttpStatus.BAD_REQUEST);
      }
      const result = await this.webbaseService.removeMany(ids);
      return {
        message: `成功删除${result.deletedCount}条记录`,
        deletedCount: result.deletedCount
      };
    } catch (error) {
      throw new HttpException(
        error.message || '批量删除模型失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 根据ID查询模型详情
   * @param id 模型ID
   * @returns 模型详情
   */
  @Get('findModuleById/:id')
  @ApiOperation({ summary: '查询模型详情' })
  @ApiResponse({ status: 200, description: '查询成功' })
  async findOne(@Param('id') id: string) {
    try {
      const result = await this.webbaseService.findOne(id);
      if (!result) {
        throw new HttpException('模型不存在', HttpStatus.NOT_FOUND);
      }
      return result;
    } catch (error) {
      throw new HttpException(
        error.message || '查询模型详情失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 更新模型
   * @param id 模型ID
   * @param updateModuleDto 更新数据
   * @returns 更新后的模型数据
   */
  @Post('updateModule/:id')
  @ApiOperation({ summary: '更新模型' })
  @ApiResponse({ status: 200, description: '更新成功' })
  async update(@Param('id') id: string, @Body() updateModuleDto: Partial<ModuleModel>) {
    try {
      const result = await this.webbaseService.update(id, updateModuleDto);
      if (!result) {
        throw new HttpException('模型不存在', HttpStatus.NOT_FOUND);
      }
      return {};
    } catch (error) {
      throw new HttpException(
        error.message || '更新模型失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 删除模型
   * @param id 模型ID
   * @returns 删除结果
   */
  @Delete('delete/:id')
  @ApiOperation({ summary: '删除模型' })
  @ApiResponse({ status: 200, description: '删除成功' })
  async remove(@Param('id') id: string) {
    try {
      const result = await this.webbaseService.remove(id);
      if (result.deletedCount === 0) {
        throw new HttpException('模型不存在', HttpStatus.NOT_FOUND);
      }
      return { message: '删除成功' };
    } catch (error) {
      throw new HttpException(
        error.message || '删除模型失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  // ==================== Cube 相关接口 ====================

  /**
   * 创建立方体组件
   * @param createCubeDto 创建立方体组件的数据
   * @returns 创建的立方体组件数据
   */
  @Post('cube')
  @ApiOperation({ summary: '创建立方体组件' })
  @ApiResponse({ status: 201, description: '创建成功' })
  async createCube(@Body() createCubeDto: Cube) {
    try {
      console.log(createCubeDto, 'createCubeDto');
      return await this.webbaseService.createCube(createCubeDto);
    } catch (error) {
      throw new HttpException(
        error.message || '创建立方体组件失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 分页查询立方体组件列表
   * @param query 查询参数
   * @returns 分页数据
   */
  @Post('cube/findAll')
  @ApiOperation({ summary: '分页查询立方体组件列表' })
  @ApiResponse({ status: 200, description: '查询成功' })
  async findAllCubes(@Body() query: any) {
    try {
      return await this.webbaseService.findAllCubes(query);
    } catch (error) {
      throw new HttpException(
        error.message || '查询立方体组件列表失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 获取全部立方体组件列表（不带分页）
   * @returns 全部立方体组件列表
   */
  @Get('cube/all')
  @ApiOperation({ summary: '获取全部立方体组件列表' })
  @ApiResponse({ status: 200, description: '查询成功' })
  async findAllCubesWithoutPagination() {
    try {
      return await this.webbaseService.findAllCubesWithoutPagination();
    } catch (error) {
      throw new HttpException(
        error.message || '查询全部立方体组件列表失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 根据ID查询立方体组件详情
   * @param id 立方体组件ID
   * @returns 立方体组件详情
   */
  @Get('cube/findCubeById/:id')
  @ApiOperation({ summary: '查询立方体组件详情' })
  @ApiResponse({ status: 200, description: '查询成功' })
  async findOneCube(@Param('id') id: string) {
    try {
      const result = await this.webbaseService.findOneCube(id);
      if (!result) {
        throw new HttpException('立方体组件不存在', HttpStatus.NOT_FOUND);
      }
      return result;
    } catch (error) {
      throw new HttpException(
        error.message || '查询立方体组件详情失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 更新立方体组件
   * @param id 立方体组件ID
   * @param updateCubeDto 更新数据
   * @returns 更新后的立方体组件数据
   */
  @Post('cube/update/:id')
  @ApiOperation({ summary: '更新立方体组件' })
  @ApiResponse({ status: 200, description: '更新成功' })
  async updateCube(@Param('id') id: string, @Body() updateCubeDto: Partial<Cube>) {
    try {
      const result = await this.webbaseService.updateCube(id, updateCubeDto);
      if (!result) {
        throw new HttpException('立方体组件不存在', HttpStatus.NOT_FOUND);
      }
      return {};
    } catch (error) {
      throw new HttpException(
        error.message || '更新立方体组件失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 删除立方体组件
   * @param id 立方体组件ID
   * @returns 删除结果
   */
  @Delete('cube/delete/:id')
  @ApiOperation({ summary: '删除立方体组件' })
  @ApiResponse({ status: 200, description: '删除成功' })
  async removeCube(@Param('id') id: string) {
    try {
      const result = await this.webbaseService.removeCube(id);
      if (result.deletedCount === 0) {
        throw new HttpException('立方体组件不存在', HttpStatus.NOT_FOUND);
      }
      return { message: '删除成功' };
    } catch (error) {
      throw new HttpException(
        error.message || '删除立方体组件失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 批量删除立方体组件
   * @param body 包含ID数组的请求体
   * @returns 删除结果
   */
  @Post('cube/batchDelete')
  @ApiOperation({ summary: '批量删除立方体组件' })
  @ApiResponse({ status: 200, description: '批量删除成功' })
  async removeManyCubes(@Body() body: { ids: string[] }) {
    try {
      const { ids } = body;
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        throw new HttpException('请提供有效的ID数组', HttpStatus.BAD_REQUEST);
      }
      const result = await this.webbaseService.removeManyCubes(ids);
      return {
        message: `成功删除${result.deletedCount}条记录`,
        deletedCount: result.deletedCount
      };
    } catch (error) {
      throw new HttpException(
        error.message || '批量删除立方体组件失败',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 获取默认模块模板内容
   * @returns 模板内容
   */
  @Get('template/default-module')
  @ApiOperation({ summary: '获取默认模块模板内容' })
  @ApiResponse({ status: 200, description: '成功获取模板内容', schema: { type: 'object', properties: { content: { type: 'string' } } } })
  @ApiResponse({ status: 500, description: '读取文件失败' })
  async getDefaultModuleTemplate() {
    try {
      return await this.webbaseService.getDefaultModuleTemplate();
    } catch (error) {
      throw new HttpException(
        error.message || '获取默认模块模板失败',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // ==================== Templates 相关接口 ====================

  /**
   * 创建新的 Templates
   * @param createTemplatesDto - 创建 Templates 的数据
   * @returns 创建的 Templates
   */
  @Post('templates')
  @ApiOperation({ summary: '创建新的 Templates' })
  @ApiResponse({ status: 201, description: 'Templates 创建成功', type: Templates })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async createTemplates(@Body() createTemplatesDto: Partial<Templates>) {
    console.log('Creating Templates:', createTemplatesDto);
    try {
      const templates = await this.webbaseService.createTemplates(createTemplatesDto);
      return {
        success: true,
        data: templates,
        message: 'Templates 创建成功',
      };
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 获取所有 Templates（支持分页和条件查询）
   * @param page - 页码
   * @param limit - 每页数量
   * @param templateName - 模板名称过滤
   * @param type - 类型过滤
   * @returns Templates 列表和分页信息
   */
  @Get('templates')
  @ApiOperation({ summary: '获取所有 Templates（支持分页和条件查询）' })
  @ApiQuery({ name: 'pageNum', required: false, description: '页码', example: 1 })
  @ApiQuery({ name: 'pageSize', required: false, description: '每页数量', example: 20 })
  @ApiQuery({ name: 'templateName', required: false, description: '模板名称过滤' })
  @ApiQuery({ name: 'type', required: false, description: '类型过滤' })
  @ApiResponse({ status: 200, description: '成功获取 Templates 列表' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async findAllTemplates(
    @Query('pageNum') pageNum?: string,
    @Query('pageSize') pageSize?: string,
    @Query('templateName') templateName?: string,
    @Query('type') type?: string,
  ) {
    try {
      const page = pageNum ? parseInt(pageNum, 10) : 1;
      const limit = pageSize ? parseInt(pageSize, 10) : 20;
      const result = await this.webbaseService.findAllTemplates(page, limit, templateName, type);
      return {
        success: true,
        ...result,
        message: '获取 Templates 列表成功',
      };
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get("templates/getDetail/:id")
  @ApiOperation({ summary: '获取 Templates 详情' })
  @ApiParam({ name: 'id', description: 'Templates ID' })
  @ApiResponse({ status: 200, description: '成功获取 Templates 详情' })
  @ApiResponse({ status: 404, description: 'Templates 不存在' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async getTemplatesDetail(@Param('id') id: string) {
    try {
      const templates = await this.webbaseService.findOneTemplates(id);
      if (!templates) {
        throw new HttpException('Templates 不存在', HttpStatus.NOT_FOUND);
      }
      return templates;
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 获取所有 Templates（不分页）
   * @param templateName - 模板名称过滤
   * @param type - 类型过滤
   * @returns Templates 列表
   */
  @Get('templates/all')
  @ApiOperation({ summary: '获取所有 Templates（不分页）' })
  @ApiQuery({ name: 'templateName', required: false, description: '模板名称过滤' })
  @ApiQuery({ name: 'type', required: false, description: '类型过滤' })
  @ApiResponse({ status: 200, description: '成功获取 Templates 列表' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async findAllTemplatesWithoutPagination(
    @Query('templateName') templateName?: string,
    @Query('type') type?: string,
  ) {
    try {
      const templates = await this.webbaseService.findAllTemplatesWithoutPagination(templateName, type);
      return {
        success: true,
        data: templates,
        message: '获取 Templates 列表成功',
      };
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 根据 ID 获取单个 Templates
   * @param id - Templates ID
   * @returns Templates 详情
   */


  /**
   * 更新 Templates
   * @param id - Templates ID
   * @param updateTemplatesDto - 更新数据
   * @returns 更新后的 Templates
   */
  @Put('templates/update/:id')
  @ApiOperation({ summary: '更新 Templates' })
  @ApiParam({ name: 'id', description: 'Templates ID' })
  @ApiResponse({ status: 200, description: 'Templates 更新成功', type: Templates })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 404, description: 'Templates 不存在' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async updateTemplates(
    @Param('id') id: string,
    @Body() updateTemplatesDto: Partial<Templates>,
  ) {
    try {
      const templates = await this.webbaseService.updateTemplates(id, updateTemplatesDto);
      return {
        success: true,
        message: 'Templates 更新成功',
      };
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 删除 Templates
   * @param id - Templates ID
   * @returns 删除结果
   */
  @Delete('templates/delete/:id')
  @ApiOperation({ summary: '删除 Templates' })
  @ApiParam({ name: 'id', description: 'Templates ID' })
  @ApiResponse({ status: 200, description: 'Templates 删除成功' })
  @ApiResponse({ status: 404, description: 'Templates 不存在' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async removeTemplates(@Param('id') id: string) {
    try {
      const result = await this.webbaseService.removeTemplates(id);
      return result;
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.NOT_FOUND,
      );
    }
  }

  /**
   * 批量删除多个 Templates
   * @param ids - Templates ID 数组
   * @returns 删除结果
   */
  @Delete('templates/batchDelete')
  @ApiOperation({ summary: '批量删除多个 Templates' })
  @ApiResponse({ status: 200, description: 'Templates 批量删除成功' })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async removeManyTemplates(@Body('ids') ids: string[]) {
    try {
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        throw new Error('请提供有效的 Templates ID 数组');
      }
      const result = await this.webbaseService.removeManyTemplates(ids);
      return result;
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message,
        },
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  /**
   * 更新预览页面内容
   * @param body - 包含内容的请求体（来源：请求体）
   * @returns 更新结果
   */
  @Post("updatePreview")
  @ApiOperation({ summary: '更新预览页面内容' })
  @ApiResponse({ status: 200, description: '预览页面更新成功' })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 500, description: '服务器错误' })
  async updatePreview(@Body() body: { content: string }) {
    try {
      if (!body.content) {
        throw new HttpException(
          {
            success: false,
            message: '内容不能为空',
          },
          HttpStatus.BAD_REQUEST,
        );
      }

      // 调用 updateWebPage 函数覆盖 web/app/pages/preview.vue 文件
      const result = updateWebPage('web/app/pages/preview.vue', body.content);

      if (result.status) {
        return {
          success: true,
          message: '预览页面更新成功',
        };
      } else {
        throw new HttpException(
          {
            success: false,
            message: result.msg,
          },
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    } catch (error) {
      throw new HttpException(
        {
          success: false,
          message: error.message || '更新预览页面失败',
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get("getIndexData")
  @Public()
  async getIndexData() {
    return await this.webbaseService.getMenusWithListDetails();
  }
}

